package com.yonyou.train.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.train.ResultJson;
import com.yonyou.train.StatusCode;
import com.yonyou.train.exception.LoginException;
import com.yonyou.train.model.Auth;
import com.yonyou.train.service.AuthService;
import com.yonyou.train.yonyouec.SyncEcUser;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yonyou.train.model.User;
import com.yonyou.train.service.UserService;


import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping(value = "/users")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    //创建线程安全的Map
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());


    /*
    接入友空间移动端，根据url代入的code获取用户信息
     */
    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public Object getUser(@RequestParam String code, HttpServletRequest request) {
        User user = userService.getUserbyCode(code);
        return ResultJson.success(StatusCode.SUCCESS, "success", user);
    }

    /**
     * 登录接口
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/session", method = RequestMethod.POST)
    public Object login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String usermobile = userService.login(map.get("mobile"), map.get("pwd"), request);
        return ResultJson.success(StatusCode.SUCCESS, "success", usermobile);
    }

    /**
     * 登出接口
     *
     * @param session_mobile
     * @param request
     * @return
     */
    @RequestMapping(value = "/session/{session_mobile}", method = RequestMethod.DELETE)
    public Object loginOut(@PathVariable String session_mobile, HttpServletRequest request) {
        userService.loginout(session_mobile, request);
        return ResultJson.success(StatusCode.SUCCESS, "success");
    }

    /**
     * 修改密码接口
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/users", method = RequestMethod.PUT)
    public Object updatepwd(@RequestBody Map<String, String> map) {
        String mobile = map.get("mobile");
        String oldpwd = map.get("oldpwd");
        String newpwd = map.get("newpwd");
        userService.updatepwd(mobile, oldpwd, newpwd);
        return ResultJson.success(StatusCode.SUCCESS, "success");
    }

    /* 同步
     * */
    @RequestMapping(value = "/sync", method = RequestMethod.GET)
    public Object synchronizeUser() {
        userService.synchronizeUser();
        authService.synchronizeAuth();
        userService.updateIndex();
        return ResultJson.success(StatusCode.SUCCESS, "success");
    }

}
